import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';

import { NameLabel, Page } from '@core/base';
import { BaseHttpService } from '@core/base/base-http.service';

import { Config, ConfigQuery, Log, LogQuery, Task, TaskQuery } from './custom.model';

@Injectable({ providedIn: 'root' })
export class CustomService {
  private baseConfigUrl = '/job/v1/configs';
  private baseTaskUrl = '/job/v1/tasks';
  private baseCommonUrl = '/job/v1/commons';

  constructor(private http: BaseHttpService) {}

  public getConfigById(configId: string): Observable<Config> {
    return this.http.get<Config>(`${this.baseConfigUrl}/${configId}`).pipe(map(data => new Config(data)));
  }

  public createConfig(config: Config): Observable<Config> {
    return this.http.post<Config>(`${this.baseConfigUrl}`, config).pipe(map(data => new Config(data)));
  }

  public updateConfig(configId: string, config: Config): Observable<Config> {
    return this.http.put<Config>(`${this.baseConfigUrl}/${configId}`, config).pipe(map(data => new Config(data)));
  }

  public deleteConfig(configId: string): Observable<any> {
    return this.http.delete<any>(`${this.baseConfigUrl}/${configId}`);
  }

  public deleteLogs(configId: string): Observable<any> {
    return this.http.delete<any>(`${this.baseTaskUrl}/${configId}/log`);
  }

  public getConfigPage(query: ConfigQuery): Observable<Page<Config>> {
    return this.http
      .get<Page<Config>>(`${this.baseConfigUrl}`, query.httpParams)
      .pipe(map(data => Object.assign(data, { content: data.content.map(e => new Config(e)) })));
  }

  public startTask(configId: string): Observable<Task> {
    return this.http.post<Task>(`${this.baseTaskUrl}/${configId}/start`, null).pipe(map(data => new Task(data)));
  }

  public stopTask(configId: string): Observable<Task> {
    return this.http.post<Task>(`${this.baseTaskUrl}/${configId}/stop`, null).pipe(map(data => new Task(data)));
  }

  public getTask(configId: string): Observable<Task> {
    return this.http.get<Task>(`${this.baseTaskUrl}/${configId}`).pipe(map(data => new Task(data)));
  }

  public getTasks(query: TaskQuery): Observable<Task[]> {
    return this.http.get<Task[]>(`${this.baseTaskUrl}`, query).pipe(map(data => data.map(e => new Task(e))));
  }

  public getLogPage(query: LogQuery): Observable<Page<Log>> {
    return this.http
      .get<Page<Log>>(`${this.baseTaskUrl}/log`, query.httpParams)
      .pipe(map(data => Object.assign(data, { content: data.content.map(e => new Log(e)) })));
  }

  public getEnum(): Observable<NameLabel[]> {
    return this.http.get<NameLabel[]>(`${this.baseCommonUrl}/enum`).pipe(map(data => data.map(e => new NameLabel(e))));
  }
}
